from datetime import datetime
from django.core.paginator import Paginator
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django_redis import get_redis_connection
from django.db import transaction
import json

from decimal import Decimal
# Create your views here.
from addresses.models import Address
from goods.models import SKU
from order.models import OrderInfo, OrderGoods


class OrdersSettlementView(View):
    def get(self, request):
        # 获取当前用户的地址
        user = request.user
        address = Address.objects.filter(user=user, is_deleted=False)
        # 从redis中获取选中状态的商品
        client = get_redis_connection('carts')
        sku_id_count = client.hgetall('carts_%s' % user.id, )

        sku_count = {}
        for sku_id, count in sku_id_count.items():
            sku_count[int(sku_id)] = int(count)
        # 获取选中的商品id
        sku_ids = client.smembers('carts_selected_%s' % user.id)
        skus = SKU.objects.filter(id__in=sku_ids)
        sku_list = []
        total_count = 0
        total_amount = 0
        for sku in skus:
            sku_list.append({
                'id': sku.id,
                'price': sku.price,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'count': sku_count[sku.id],
                'total_amount': sku_count[sku.id] * sku.price
            })
            total_count += sku_count[sku.id]
            total_amount += sku_count[sku.id] * sku.price
        transit = 10
        payment_amount = total_amount + transit
        data = {
            'addresses': address,
            'payment_amount': payment_amount,
            'total_count': total_count,
            'total_amount': total_amount,
            'transit': transit,
            'sku_list': sku_list
        }

        return render(request, 'place_order.html', data)


class OrdersCommitView(View):
    def post(self, request):
        data = request.body.decode()
        data_dict = json.loads(data)
        address_id = data_dict.get('address_id')
        pay_method = data_dict.get('pay_method')
        try:
            addresses = Address.objects.get(id=address_id)
        except:
            return JsonResponse({'error': '地址不存在'}, status=400)
        user = request.user
        # 生成订单编号
        order_id = datetime.now().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)
        # 开启事物
        with transaction.atomic():
            # 设置保存点
            save_point = transaction.savepoint()
            try:
                # 生成订单的基本信息
                order = OrderInfo.objects.create(
                    order_id=order_id,
                    user=user,
                    address=addresses,
                    total_count=0,
                    total_amount=Decimal(0),
                    freight=Decimal(10),
                    pay_method=pay_method,
                    status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY'] else OrderInfo.ORDER_STATUS_ENUM['UNSEND']
                )
                # 从redis获取选中状态的商品
                client = get_redis_connection('carts')
                sku_id_count = client.hgetall('carts_%s' % user.id)
                sku_count = {}
                for sku_id, count in sku_id_count.items():
                    sku_count[int(sku_id)] = int(count)
                    # 获取选中的sku_id
                sku_ids = client.smembers('carts_selected_%d' % user.id)
                # 遍历商品订单商品表
                for sku_id in sku_ids:
                    while True:
                        #  获取当前商品的库存
                        sku = SKU.objects.get(id=sku_id)
                        stock_old = sku.stock
                        # 选中数量
                        count = sku_count[sku.id]

                        sales_old = sku.sales
                        if count > stock_old:
                            return JsonResponse({'message': '库存不足'}, status=400)
                        # 修改sku商品库存和销量
                        stock_new = sku.stock - count
                        sales_new = sku.sales + count
                        # 再次按照旧的库存获取商品,获取到更新,获取不到返回再次操作(乐观锁)
                        res = SKU.objects.filter(id=sku_id, stock=stock_old).update(stock=stock_new, sales=sales_new)
                        if res == 0:
                            continue
                        # 修改spu表中的总销量
                        sku.spu.sales += count
                        sku.spu.save()

                        order.total_count += count
                        order.total_amount += sku.price * count
                        # 保存订单商品数据
                        OrderGoods.objects.create(
                            order=order,
                            sku=sku,
                            count=count,
                            price=sku.price
                        )
                        break

                    order.total_amount += order.freight
                    order.save()
            except:
                # 回滚到保存点
                transaction.savepoint_rollback(save_point)
            else:
                # 事物结束提交数据
                transaction.savepoint_commit(save_point)
                # 删除购物车选中状态的商品
                client.hdel('carts_%s' % user.id, *sku_ids)
                client.srem('carts_selected_%d' % user.id, *sku_ids)

            return JsonResponse({'code': 0, 'order_id': order_id})

# order_id=20190917021201000000001&payment_amount=6698&pay_method=2
class OrdersSuccessView(View):
    def get(self,request):
        order_id = request.GET.get('order_id')
        payment_amount = request.GET.get('payment_amount')
        pay_method = request.GET.get('pay_method')

        data = {
            'order_id':order_id,
            'payment_amount':payment_amount,
            'pay_method':pay_method


        }
        return render(request,'order_success.html',data)


class OrdersInfoView(View):
    def get(self,request,pk):
        user = request.user
        orders = OrderInfo.objects.filter(user =user)
        for order in orders:

            order.details = []
            order_goods = order.skus.all()
            for order_good in order_goods:
                order.details.append(
                    {

                        'name':order_good.sku.name,
                        'price':order_good.sku.price,
                        'default_image_url':order_good.sku.default_image.url,
                        'count':order_good.count,
                        'total_amount':order_good.count*order_good.sku.price
                    }
                )
        page = Paginator(orders,5)
        order_pages = page.page(pk)
        data = {
            'page': order_pages,
            'page_num': pk,
            'total_page': page.num_pages

        }



        return render(request,'user_center_order.html',data)


class OrdersCommentView(View):
    def get(self,request):

        order_id = request.GET.get('order_id')
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except:
            return JsonResponse({'error':'订单不存在'},status=400)

        goods_order = OrderGoods.objects.filter(is_commented=False)

        skus = []

        for good in goods_order:
            skus.append({
                'name': good.sku.name,
                'price': str(good.price),
                'count': good.count,
                'comment': good.comment,
                'score': good.score,
                'is_anonymous': str(good.is_anonymous),
                'is_commented': str(good.is_commented),
                'default_image_url': good.sku.default_image.url,
                'order_id': order_id,
                'sku_id': good.sku.id
            })

        return render(request,'goods_judge.html',{'skus':skus})

    def post(self,request):

        # comment: "sgasgas"
        # is_anonymous:false
        # order_id:"20190917015347000000001"
        # score:5
        # sku_id: 6

        data = request.body.decode()
        data_dict = json.loads(data)
        comment = data_dict.get('comment')
        is_anonymous = data_dict.get('is_anonymous')
        order_id= data_dict.get('order_id')
        score = data_dict.get('score')
        sku_id = data_dict.get('sku_id')

        try:
            SKU.objects.get(id = sku_id)
        except:
            return JsonResponse({'error':'商品不存在'})

        try:
            OrderInfo.objects.get(order_id=order_id)
        except:
            return JsonResponse({'error':'商品不存在'})

        OrderGoods.objects.filter(order_id=order_id).update(comment=comment,score=score,is_anonymous=is_anonymous,is_commented=True)

        return JsonResponse({'code':0})


